package Threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

import Debug.Debug;
import Structs.Log;
import Structs.Msg_broad;

public class S_TCP_REQ_LISTEN implements Runnable {
	
	private Thread Mylife;
	private int port;
	private Hashtable Clients;
	private Hashtable Tasks;
	private Hashtable OnlineClients;
	private BlockingQueue<Thread> GrimReaper;
	private BlockingQueue<Msg_broad> requests;
	private BlockingDeque<Log> log;
	
	public S_TCP_REQ_LISTEN(int port, 
							Hashtable Clients, 
							Hashtable Tasks, 
							BlockingQueue<Thread> GrimReaper,
							BlockingQueue<Msg_broad> requests, 
							BlockingDeque<Log>log,
							Hashtable OnlineClients ) {
		// TODO Auto-generated constructor stub
		this.GrimReaper = GrimReaper;
		this.Clients = Clients;
		this.Tasks = Tasks;
		this.port = port;
		this.log = log;
		this.requests = requests;
		this.OnlineClients = OnlineClients;
		this.Mylife = new Thread(this);
		this.Mylife.start();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			
			ServerSocket listensocket = new ServerSocket(port);
			System.out.println("[SERVER]: TCP server ready for business at "+port);
			do{
				Socket client = listensocket.accept();
				if(new Debug().isDebug())
					System.out.println();
				new S_TCP_in_out(client, GrimReaper, Clients, Tasks,requests,log, OnlineClients);
			}while(true);
		} catch (IOException e){
			if(new Debug().isDebug())
				System.out.println("IO Error Req Listener");
		} finally {
			GrimReaper.add(this.Mylife);
		}
	}
}
